package com.iwith.dongmoon.activity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;

import com.google.gson.Gson;
import com.iwith.dongmoon.gsonlist.BoardList;
import com.iwith.dongmoon.gsonlist.CategoryList;
import com.iwith.dongmoon.util.ApiCode;
import com.iwith.dongmoon.util.HttpRequestor;
import com.iwith.dongmoon.util.RequestGson;
import com.iwith.dongmoon.util.ResultCode;
import com.iwith.dongmoon.util.ThreadInterface;
import com.iwith.dongmoon.util.ThreadTask;

public class UpdateNewsActivity extends Activity implements OnTouchListener, OnClickListener{
	public static final int REQUEST_GALLERY = 1;
	public static final int REQUEST_CAMERA = 0;
	
//	final String [] typeName={ "경조사", "모임", "업체홍보", "소모임" };
	final String [] typeName={ "모임", "자유게시판" };
	
	private Spinner meetingTypeSpinner;
	private Spinner meetingCategorySpinner;
	private LinearLayout layout;
	private EditText address;
	private EditText date;
	private EditText time;
	private EditText subject;
	private EditText content;
	private Button imageBt;
	private Button updateNewsBt;
	private Button cancelBt;

	private String imagePath="no image";

	private String meetingType=null;
	private String meetingCategory=null;

	static final int DATE_DIALOG_ID = 0;
	static final int TIME_DIALOG_ID = 1;

	private int mYear;
	private int mMonth;
	private int mDay;
	private int mHour;
	private int mMinute;

	private String boardname;
	private String userid;
	private String code;
	
	private Context mContext;
	
	private AlertDialog.Builder mAlertDialog;
	
	private File imageFile;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// TODO Auto-generated method stub
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.updatenews);

		Initialize();
	}
	
	private void Initialize(){
		mContext=this;
		boardname = getIntent().getExtras().getString("boardname");
		code = getIntent().getExtras().getString("code");
		userid=getIntent().getExtras().getString("userid");
		
		layout = (LinearLayout) findViewById(R.id.updatenews_layout);
		address = (EditText) layout.findViewById(R.id.updatenews_address);
		date = (EditText) layout.findViewById(R.id.updatenews_date);
		time = (EditText) layout.findViewById(R.id.updatenews_time);
		subject = (EditText) layout.findViewById(R.id.updatenews_subject);
		content = (EditText) layout.findViewById(R.id.updatenews_content);
		imageBt = (Button) layout.findViewById(R.id.updatenews_imagepath);
		updateNewsBt = (Button) layout.findViewById(R.id.updatenews_updatebt);
		cancelBt = (Button) layout.findViewById(R.id.updatenews_cancelbt);
		meetingTypeSpinner = (Spinner) layout.findViewById(R.id.updatenews_newstype);
		meetingCategorySpinner = (Spinner) layout.findViewById(R.id.updatenews_newscategory);
		mAlertDialog = new AlertDialog.Builder(this);
		
		setMeetingTypeSpinner(boardname);		
		setCategorySpinner(meetingType, boardname);


		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);
		mHour = c.get(Calendar.HOUR_OF_DAY);
		mMinute = c.get(Calendar.MINUTE);

		updateDisplay();
		layout.setOnTouchListener(this);
		date.setOnTouchListener(this);
		time.setOnTouchListener(this);
		updateNewsBt.setOnClickListener(this);
		imageBt.setOnClickListener(this);
		cancelBt.setOnClickListener(this);
	}

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			// TODO Auto-generated method stub
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			updateDisplay();
		}
	};

	private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			// TODO Auto-generated method stub
			mHour = hourOfDay;
			mMinute = minute;
			updateDisplay();
		}
	};

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);
		case TIME_DIALOG_ID:
			return new TimePickerDialog(this, mTimeSetListener, mHour, mMinute, false);
		}
		return null;
	}

	@Override
	public void onResume() {
		super.onResume();
		ThreadTask.onFinishAll();
		setCategorySpinner(meetingType, boardname);
	}
	
	@Override
	public void onPause(){
		super.onPause();
		ThreadTask.onFinishAll();
	}
	
	private void writeContent(){
		ThreadInterface threadInterface = new ThreadInterface(){
			BoardList boardList;
			public void onThread() {
				Gson gson = new Gson();
				HttpRequestor data = null;
				try {
					String api = null;
					if (meetingType.equals(typeName[0]) == true) {
//						api = ApiCode.API_OCCASION+"/insert";
//					} else if (meetingType.equals(typeName[1]) == true) {
						api = ApiCode.API_MEETING+"/insert";
//					} else if (meetingType.equals(typeName[2]) == true) {
//						api = ApiCode.API_ADVERTISEMENT+"/insert";
//					} else if(meetingType.equals(typeName[3]) == true) {
//						api = ApiCode.API_GROUP+"/insert";
					} else if (meetingType.equals(typeName[1]) == true) {
						api = ApiCode.API_BULLETIN+"/insert";
					}
					data = new HttpRequestor(new URL(getString(R.string.api_url) + api));
				} catch (MalformedURLException e) {
					e.printStackTrace();
				}

				if (data != null) {
					data.addParameter("userid", userid);
					data.addParameter("category", meetingCategory);
					data.addParameter("subject", subject.getText().toString());
					data.addParameter("content", content.getText().toString());
					data.addParameter("email", content.getText().toString());
					data.addParameter("address", address.getText().toString());
					data.addParameter("datetime", date.getText().toString()	+ " " + time.getText().toString());
					data.addFile("picture", imageFile);
					try {
						InputStream is = data.sendMultipartPost((Activity) mContext);
						BufferedReader bin = new BufferedReader(new InputStreamReader(is));
						String line = bin.readLine();
						boardList = gson.fromJson(line, BoardList.class);
					} catch (IOException e) {
						e.printStackTrace();
					} finally {
					}
				}
			}
			public void onThreadEnd() {
				if(boardList!=null){
					if(boardList.getResultCode().equals(ResultCode.SUCCESS)==true){
						Toast.makeText(mContext, "Writing News is Success", Toast.LENGTH_LONG).show();
						/*try{
							mContext.wait(2000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						} finally {
						}*/
						finish();
					}
				}
				
			}
		};
		ThreadTask task = new ThreadTask((Activity)mContext, threadInterface);
		task.execute();
	}
	
	private void setMeetingTypeSpinner(final String boardname){
		ArrayList<String> typelist=new ArrayList<String>();
		if(code.equals(ApiCode.NEWS)==true)
		{
			typelist.add(typeName[0]);
			typelist.add(typeName[1]);
//			typelist.add(typeName[2]);
		}
//		else if(code.equals(ApiCode.GROUP)==true){
//			typelist.add(typeName[3]);
//		}
		ArrayAdapter<String> typeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, typelist);
		meetingTypeSpinner.setAdapter(typeAdapter);
		typeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		meetingTypeSpinner.setSelection(0);
		meetingType=meetingTypeSpinner.getSelectedItem().toString();
		
		meetingTypeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent,
					View view, int position, long id) {
				// TODO Auto-generated method stub
				meetingType = (String) meetingTypeSpinner.getSelectedItem().toString();
				setCategorySpinner(meetingType, boardname);
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}

		});
	}

	private void setCategorySpinner(final String meetingtype, final String boardname) {
		ThreadInterface threadInterface = new ThreadInterface(){
			CategoryList categoryList;
			RequestGson requestGson = new RequestGson();
			public void onThread() {
				// TODO Auto-generated method stub
				String api_name=null;
				if (meetingtype.equals(typeName[0]) == true) {
//					api_name=ApiCode.API_OCCASION;
//					categoryList = requestGson.getCategoryGsonBySendingAPI(mContext, api_name, "/category");
//				} else if (meetingtype.equals(typeName[1]) == true) {
					api_name=ApiCode.API_MEETING;
					categoryList = requestGson.getCategoryGsonBySendingAPI(mContext, api_name, "/category");
//				} else if (meetingtype.equals(typeName[2]) == true) {
//					api_name=ApiCode.API_ADVERTISEMENT;
//					categoryList = requestGson.getCategoryGsonBySendingAPI(mContext, api_name, "/category");
//				} else if (meetingtype.equals(typeName[3]) == true) {
				} else if(meetingtype.equals(typeName[1]) == true) {
					categoryList=null;
				}
			}

			public void onThreadEnd() {
				// TODO Auto-generated method stub
				ArrayList<String> categoryStrings = new ArrayList<String>();
				if(categoryList==null) {
					categoryStrings.add(meetingType);
					meetingCategorySpinner.setEnabled(false);
					address.setEnabled(false);
					date.setEnabled(false);
					time.setEnabled(false);
				} else if(categoryList.getResultCode().equals(ResultCode.SUCCESS)==true){
					for (int i = 0; i < categoryList.getContent().size(); i++) {
						categoryStrings.add(categoryList.getContent().get(i));
					}
				}
				
				if (categoryStrings.size() > 0) {
					ArrayAdapter<String> typeAdapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_item, categoryStrings);
					meetingCategorySpinner.setAdapter(typeAdapter);
					typeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					meetingCategorySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

						public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
						// TODO Auto-generated method stub
							meetingCategory = meetingCategorySpinner.getSelectedItem().toString();
						}

						public void onNothingSelected(AdapterView<?> arg0) {
							// TODO Auto-generated method stub
						}

					});
				}
			}
			
		};
		
		ThreadTask task = new ThreadTask((Activity)mContext, threadInterface);
		task.execute();
	}


	public void alertToast(String message) {
		Toast alertMessage = Toast.makeText(UpdateNewsActivity.this, message, Toast.LENGTH_SHORT);
		alertMessage.show();
	}

	private void updateDisplay() {
		date.setText(String.format("%04d-%02d-%02d", mYear, mMonth + 1, mDay));
		time.setText(String.format("%02d:%02d", mHour, mMinute));
	}
	
	@TargetApi(8)
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode != RESULT_OK)
			return;

		if (requestCode == REQUEST_GALLERY) {
			Uri imageUri = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };

			Cursor cursor = getContentResolver().query(imageUri, filePathColumn, null, null, null);
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			String filePath = cursor.getString(columnIndex);
			cursor.close();

			Bitmap bitmap = BitmapFactory.decodeFile(filePath);// , option);

			// 이미지 생성
			File imageFile = new File(filePath);

			File path = null;
			String state = Environment.getExternalStorageState();
			if (state.equals(Environment.MEDIA_MOUNTED)) {
				path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
			} else {
				path = getFilesDir();
			}
			if (!path.exists())
				path.mkdirs();

			this.imageFile=imageFile;
			//uploadPicture(imageFile, thumbnailFile);

		} else if (requestCode == REQUEST_CAMERA) {
			// intent 의 여분 데이터로 저장된 비트맵 이미지를 얻는다. Bitmap bitmap = (Bitmap)
			Bitmap bitmap = (Bitmap) data.getExtras().get("data");

			File path = null;
			String state = Environment.getExternalStorageState();
			if (state.equals(Environment.MEDIA_MOUNTED)) {
				path = Environment
						.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
			} else {
				path = getFilesDir();
			}
			if (!path.exists())
				path.mkdirs();

			File imageFile = new File(path, "iwith_image_" + userid + ".jpg");

			FileOutputStream imageOut = null;
			try {
				imageOut = new FileOutputStream(imageFile.getPath());
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (imageOut != null) {
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, imageOut);
			}

			this.imageFile=imageFile;
			//uploadPicture(imageFile, thumbnailFile);
		}
	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v.getId()==updateNewsBt.getId()){
			if (meetingType.length() == 0) {
				alertToast("모임 종류를 선택하세요");
				return;
			} else if (meetingCategory.length() == 0) {
				alertToast("모임 내용을 선택하세요");
				return;
//			} else if (address.getText().length() == 0) {
//				alertToast("장소를 입력해주세요");
//				return;
//			} else if (date.getText().length() == 0) {
//				alertToast("날짜를 입력해주세요");
//				return;
//			} else if (time.getText().length() == 0) {
//				alertToast("시간을 입력해주세요");
//				return;
			} else if (subject.getText().length() == 0) {
				alertToast("제목을 입력해주세요");
				return;
			} else if (content.getText().length() == 0) {
				alertToast("내용을 입력해주세요");
				return;
			}
			
			writeContent();
		} else if(v.getId()==cancelBt.getId()){
			finish();
		} else if(v.getId()==imageBt.getId()){
			final String items[] = { "앨범에서 불러오기", "찍어서 올리기", "취소" };
			mAlertDialog.setTitle("사진등록하기");
			mAlertDialog.setSingleChoiceItems(items, 0,	new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					Intent intent = null;
					switch (whichButton) {
					case 0:
						intent = new Intent(Intent.ACTION_PICK);
						intent.setType("image/*");
						startActivityForResult(intent, REQUEST_GALLERY);
						break;

					case 1:
						intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
						startActivityForResult(intent, REQUEST_CAMERA);
						break;
					}
					dialog.dismiss();
				}
			});
			mAlertDialog.show();
		}
	}

	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		if(v.getId()==layout.getId()){
			InputMethodManager padControl;
			padControl = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			padControl.hideSoftInputFromWindow(layout.getWindowToken(), 0);
			return true;
		} else if(v.getId()==date.getId()){
			showDialog(DATE_DIALOG_ID);
			return true;
		} else if(v.getId()==time.getId()){
			showDialog(TIME_DIALOG_ID);
			return true;
		}
		
		return false;
	}
}
